#ifndef SQL_CONNECTOR_H
#define SQL_CONNECTOR_H
#include<mysql-cppconn-8/jdbc/cppconn/driver.h>
#include <mysql-cppconn-8/jdbc/cppconn/statement.h>
#include <mysql-cppconn-8/jdbc/cppconn/prepared_statement.h>
#include <mysql-cppconn-8/jdbc/cppconn/resultset.h>
#include <iostream>
#include <string>
#include <exception>
#include <vector>
#include<queue>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<functional>
#include<atomic>

#include "campus_sql_define.h"


class CampusSqlConnector
{
public:
    static CampusSqlConnector* getInstance();
    void setObserver(CampusSqlConnectorObserver* observer);

    int init(std::string const &dbName = "mydatabase");
    inline bool checkConnected();

    int run();
    int wait();
    
    void stop();
    void exec(sqlEvent const& sqlEvent_);
    void exec(std::string const &sql, sqlType type, void *userData);
    void exec(std::string const &sql, sqlType type, const std::vector<std::string>& params, void *userData);
    

protected:
    // 插入数据（参数化查询版本）
    void insert(const std::string &sqlString, const std::vector<std::string>& params, void* userData);

    // 更新数据（参数化查询版本）
    void update(const std::string &sqlString, const std::vector<std::string>& params, void* userData);

    // 查看数据（参数化查询版本）
    void select(const std::string &sql, const std::vector<std::string>& params, 
               std::vector<std::vector<std::pair<std::string, std::string>>> &result, void* userData);

protected:
    sql::Driver *driver;                  // 驱动
    std::unique_ptr<sql::Connection> con; // 连接数据库
    
    std::queue<sqlEvent> sqlQueue;
    std::mutex mutex_;
    std::condition_variable cv_;
    
    std::thread* thread_ = nullptr;
    std::atomic<bool> running_ = {false};

    CampusSqlConnectorObserver* observer_ = nullptr;

private:
    explicit CampusSqlConnector();
    virtual ~CampusSqlConnector();
};

#endif
